/*
Copyright (C) 2009-2011 Xanadu Development Team

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; version 2
of the License.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

#pragma once

#include "../../MySQL++/mysql++.h"
#include "../../MySQL++/cpool.h"

using namespace std;

class SimpleConnectionPool : public mysqlpp::ConnectionPool
{
public:
	SimpleConnectionPool(const char* database, const char* host, const char* username, const char* password) :
	conns_in_use_(0),
	db_(database ? database : "" ),
	server_(host ? host : ""),
	user_(username ? username : ""),
	password_(password ? password : "")
	{
	}

	~SimpleConnectionPool(){
		clear();
	}
	// Do a simple form of in-use connection limiting: wait to return
	// a connection until there are a reasonably low number in use
	// already.  Can't do this in create() because we're interested in
	// connections actually in use, not those created.  Also note that
	// we keep our own count; ConnectionPool::size() isn't the same!

	mysqlpp::Connection* grab() {
		while (conns_in_use_ > 24) {
			Sleep(1000);
		}
		++conns_in_use_;
		return mysqlpp::ConnectionPool::grab();
	}

	void release(const mysqlpp::Connection* pc) {
		mysqlpp::ConnectionPool::release(pc);
		--conns_in_use_;
	}

protected:
	mysqlpp::Connection* create()
	{
		return new mysqlpp::Connection(
				db_.empty() ? 0 : db_.c_str(),
				server_.empty() ? 0 : server_.c_str(),
				user_.empty() ? 0 : user_.c_str(),
				password_.empty() ? "" : password_.c_str());
	}

	void destroy(mysqlpp::Connection* cp){
		delete cp;
	}

	unsigned int max_idle_time()
	{
		// Set our idle time at an example-friendly 3 seconds.  A real
		// pool would return some fraction of the server's connection
		// idle timeout instead.
		return 3;
	}

private:
	unsigned int conns_in_use_;
	std::string db_, server_, user_, password_;
};